//
//  UserAccountViewModel.swift
//  weiboLQ
//
//  Created by 半缘君 on 15/12/9.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    /// 单例
    static let shareAccountModel:UserAccountViewModel = UserAccountViewModel()
    /// 用户模型
    var account:UserAccountModel?

    /// 解档
   private init () {
        account =  NSKeyedUnarchiver.unarchiveObjectWithFile(accountInfoPath) as? UserAccountModel
    if isExpired {
        account = nil
    }
}
    ///是否登录成功
    var isLogin:Bool {
        return account?.access_token != nil && (!isExpired)
    }
     /// 获取缓存文件路径
    var accountInfoPath:String {
        get {
        var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString
        path = path.stringByAppendingPathComponent("account.plist")
        return path as String
            
        }
    }
    /// 返回有效的token 
    var accountToken:String? {
        if isExpired {
            return nil
        }
        return account?.access_token
    }
/// 判断是否过期
    var isExpired: Bool {
        
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return false
        } else {
            print("过期了")
              account?.access_token = nil
        return true
        }
    }

}



// MARK: - 网络方法
extension UserAccountViewModel{
    /// 根据code获取里令牌并且根据令牌获取用户数据
    ///
    /// - parameter code:     code
    /// - parameter finished: 回调
    func loadAccessTokenAndUserInfo (code:String,finished:(isSuccess:Bool) -> ()) {
        NetworkTools.shareNetworkTools.loadAccessToken(code){
            (result, error) -> () in
            if error != nil {
                finished(isSuccess: false)
                print(error)
                return
            } else {
                //令牌
                self.account = UserAccountModel(dict: result as! Dictionary)
                //                print(account)
                //https://api.weibo.com/2/users/show.json
                self.loadUserInfo(self.account!, finished: finished)
            }
            
        }
    }
    /// 加载用户信息
    ///
    /// - parameter account:  用户模型
    /// - parameter finished: 回调
    func loadUserInfo (account:UserAccountModel,finished:(isSuccess:Bool) ->()) {
        
        NetworkTools.shareNetworkTools.loadUserInfo(account, finished: { (result, error) -> Void in
            if error != nil {
                finished(isSuccess: false)
                print(error)
            } else {
                //                        print(result)
                //avatar_large
                //screen_name
                guard let dict = result as? [String:AnyObject] else {
                    
                    finished(isSuccess: false)
                    //http://www.wang1huan2.icoc.cc
                    let error = NSError(domain: "cc.icoc.wang1huan2", code: -451481, userInfo: ["error":"result 类型不匹配"])
                    print(error)
                    return
                }
                //为账户模型赋值
                self.account!.avatarLarge = dict["avatar_large"] as? String
                self.account!.screenName = dict["screen_name"] as? String
                
                NSKeyedArchiver.archiveRootObject(account, toFile: self.accountInfoPath)
                //                print(self.account)
                finished(isSuccess: true)
            }
        })
    }
}